package com.txunda.zhuohired.fgt.user;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ants.theantsgo.config.Settings;
import com.ants.theantsgo.gson.GsonUtil;
import com.ants.theantsgo.view.inScroll.ListViewForScrollView;
import com.bumptech.glide.Glide;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.synnapps.carouselview.CarouselView;
import com.synnapps.carouselview.ImageListener;
import com.txunda.zhuohired.R;
import com.txunda.zhuohired.adapter.user.home.HomeClassifyAdapter;
import com.txunda.zhuohired.adapter.user.home.HomeListAdapter;
import com.txunda.zhuohired.adapter.user.home.HomeViewPagerAdapter;
import com.txunda.zhuohired.aty.user.home.JobPurposeAty;
import com.txunda.zhuohired.aty.user.home.SearchAty;
import com.txunda.zhuohired.aty.user.home.SelectCityAty;
import com.txunda.zhuohired.aty.user.home.TodayNewJobAty;
import com.txunda.zhuohired.base.BaseFgt;
import com.txunda.zhuohired.bean.common.RecruitBean;
import com.txunda.zhuohired.bean.user.home.HomeBean;
import com.txunda.zhuohired.http.pst.MemberHomePst;
import com.txunda.zhuohired.util.ScreenUtil;
import com.txunda.zhuohired.view.CustomViewPager;
import com.txunda.zhuohired.view.IndicatorView;
import com.txunda.zhuohired.view.ObservableScrollView;
import com.txunda.zhuohired.view.VerticalTextview;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * 创建人： Txd_Cjh
 * 创建时间： 2018/2/26 14:57
 * 功能描述：首页
 * 联系方式：jiahuanchen@126.com
 */

public class HomeFgt extends BaseFgt implements ObservableScrollView.ScrollViewListener {
    /**
     * 标题栏
     */
    @ViewInject(R.id.ll_home_tittle)
    private LinearLayout ll_home_tittle;
    /**
     * 首页定位
     */
    @ViewInject(R.id.tv_home_tittle_city)
    private TextView tv_home_tittle_city;
    /**
     * 搜索框
     */
    @ViewInject(R.id.ll_home_title_search)
    private LinearLayout ll_home_title_search;
    /**
     * ObservableScrollView
     */
    @ViewInject(R.id.home_obs_scroll)
    private ObservableScrollView home_obs_scroll;
    /**
     * 分类
     */
    @ViewInject(R.id.view_pager_fgt_home)
    private CustomViewPager view_pager_fgt_home;

    @ViewInject(R.id.entrance_indicator_fgt_home)
    private IndicatorView entrance_indicator_fgt_home;

    @ViewInject(R.id.ll_view_pager)
    private LinearLayout ll_view_pager;
    /**
     * 滚动TextView
     */
    @ViewInject(R.id.vertical_view_fgt_home)
    private VerticalTextview vertical_view_fgt_home;
    /**
     * listView
     */
    @ViewInject(R.id.lv_home)
    private ListViewForScrollView lv_home;
    /**
     * 悬浮职位设置
     */
    @ViewInject(R.id.ll_home_job_setting)
    private LinearLayout ll_home_job_setting;

    @ViewInject(R.id.iv_home_on)
    private ImageView iv_home_on;
    /**
     * 春招
     */
    @ViewInject(R.id.tv_home_spring_name)
    private TextView tv_home_spring_name;
    @ViewInject(R.id.tv_home_spring_tittle)
    private TextView tv_home_spring_tittle;
    @ViewInject(R.id.iv_home_spring)
    private ImageView iv_home_spring;
    /**
     * 热门
     */
    @ViewInject(R.id.tv_home_hot_name)
    private TextView tv_home_hot_name;
    @ViewInject(R.id.tv_home_hot_tittle)
    private TextView tv_home_hot_tittle;
    @ViewInject(R.id.iv_home_hot)
    private ImageView iv_home_hot;

    private CarouselView layout_banner_carouse;
    private CarouselView layout_banner_carouse2;
    private int allHeight;//轮播图高度
    private int allHeight2;//轮播图高度
    private List<HomeBean.DataBean.HomePicBean> imageList;
    private List<HomeBean.DataBean.PicListBean> imageList2;
    public static final int HOME_ENTRANCE_PAGE_SIZE = 10;//首页菜单单页显示数量
    private List<HomeBean.DataBean.ModulesBean> iconList;
    private List<String> nameList;
    private String[] dataName = {"每日新职位", "企业直聘", "文职专区", "兼职计划", "全部职位"};
    private List<String> verticalList;

    private HomeListAdapter homeListAdapter;
    private List<String> tagList;
    private String[] tagStr = {"每周双休", "班车接送", "五险一金"};
    private final static int REQUESTCODE = 1;//选择城市
    private MemberHomePst memberHomePst;
    private String token = "";//用户token
    private int types = 1;
    private List addList = new ArrayList();
    private List<HomeBean.DataBean.ArticleBean> articleList;
    private List<RecruitBean> recruitList;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            addList = (List) message.obj;
            vertical_view_fgt_home.setTextList(addList);
            vertical_view_fgt_home.setText(15, 0, Color.GRAY);//设置属性
            vertical_view_fgt_home.setTextStillTime(3000);//设置停留时长间隔
            vertical_view_fgt_home.setAnimTime(300);//设置进入和退出的时间间隔
            vertical_view_fgt_home.startAutoScroll();

            vertical_view_fgt_home.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    //                    bundle = new Bundle();
                    //                    if (contentArrayList.size() != 0) {
                    //                        if (!TextUtils.isEmpty(contentArrayList.get(position).getUrl())) {
                    //                            bundle.putString("url", contentArrayList.get(position).getUrl());
                    //                            startActivity(HomeInformationDetailsAty.class, bundle);
                    //                        }
                    //                    }
                }
            });

            return false;
        }
    });
    private String tittle_two = "";
    private String tittle_one = "";
    private Bundle bundle;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initHeight();
        ll_home_tittle.getBackground().mutate().setAlpha(0);
        tv_home_tittle_city.setTextColor(getResources().getColor(R.color.white));
        Drawable nav_up1 = getResources().getDrawable(R.mipmap.icon_location_white);
        nav_up1.setBounds(0, 0, nav_up1.getMinimumWidth(), nav_up1.getMinimumHeight());
        tv_home_tittle_city.setCompoundDrawables(nav_up1, null, null, null);
        ll_home_title_search.setBackgroundResource(R.drawable.shape_home_tittle_bg);
        home_obs_scroll.setScrollViewListener(HomeFgt.this);

    }

    @Override
    @OnClick({R.id.tv_home_job_close, R.id.iv_home_on, R.id.tv_home_tittle_city, R.id.ll_home_title_search, R.id
            .tv_home_purpose, R.id.tv_home_job_setting, R.id.ll_home_spring, R.id.ll_home_hot})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_home_job_close://关闭悬浮职位设置
                ll_home_job_setting.setVisibility(View.GONE);
                break;
            case R.id.iv_home_on://返回顶部
                home_obs_scroll.scrollTo(0, 0);
                home_obs_scroll.smoothScrollTo(0, 0);
                break;
            case R.id.tv_home_tittle_city://选择城市
                //                startActivityForResult(SelectCityAty.class, null, REQUESTCODE);
                startActivity(SelectCityAty.class, null);
                break;
            case R.id.ll_home_title_search://搜索
                startActivity(SearchAty.class, null);
                break;
            case R.id.tv_home_job_setting://立即设置
                startActivity(JobPurposeAty.class, null);
                break;
            case R.id.tv_home_purpose://求职意向
                startActivity(JobPurposeAty.class, null);
                break;
            case R.id.ll_home_spring://春招
                bundle = new Bundle();
                bundle.putString("tittle_name", tittle_one);
                startActivity(TodayNewJobAty.class, bundle);
                break;
            case R.id.ll_home_hot://热招
                bundle = new Bundle();
                bundle.putString("tittle_name", tittle_two);
                startActivity(TodayNewJobAty.class, bundle);
                break;
        }
    }

    @Override
    protected void immersionInit() {
        showStatusBar(R.id.ll_home_tittle);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fgt_home;
    }

    @Override
    protected void initialized() {
        memberHomePst = new MemberHomePst(this);
        token = application.getUserInfo().get("data");
        imageList = new ArrayList();
        iconList = new ArrayList<>();
        verticalList = new ArrayList<>();
        imageList2 = new ArrayList<>();
        recruitList = new ArrayList<>();

    }

    @Override
    public void onResume() {
        super.onResume();
        initHttp();
        //        vertical_view_fgt_home.startAutoScroll();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        vertical_view_fgt_home.stopAutoScroll();
    }

    private void initAdapter() {
        homeListAdapter = new HomeListAdapter(getActivity(), recruitList);
        lv_home.setAdapter(homeListAdapter);
        //        lv_home.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        //            @Override
        //            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //                L.e("========走了么========");
        //                startActivity(JobDetailsAty.class, null);
        //            }
        //        });
    }

    /**
     * 轮播图初始化
     */
    private void initBanner() {
        layout_banner_carouse = getActivity().findViewById(R.id.layout_banner_carouse);
        layout_banner_carouse.setImageListener(new ImageListener() {//点击事件
            @Override
            public void setImageForPosition(int position, ImageView imageView) {
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(getActivity()).load(imageList.get(position).getUrl()).error(R.mipmap.icon_defult_bg)
                        .placeholder(R.mipmap.icon_defult_bg).dontAnimate().into(imageView);
            }
        });
        /**
         * 设置轮播图高度
         */
        allHeight = Settings.displayWidth / 2;//轮播图高度
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Settings.displayWidth,
                allHeight);
        layout_banner_carouse.setLayoutParams(layoutParams);
        /**
         * 轮播图设置
         */
        layout_banner_carouse.setPageCount(imageList.size());//轮播图数量

    }

    /**
     * 轮播图初始化
     */
    private void initBanner2() {
        layout_banner_carouse2 = getActivity().findViewById(R.id.layout_banner_carouse2);
        layout_banner_carouse2.setImageListener(new ImageListener() {//点击事件
            @Override
            public void setImageForPosition(int position, ImageView imageView) {
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(getActivity()).load(imageList2.get(position).getUrl()).error(R.mipmap.icon_defult_bg)
                        .placeholder(R.mipmap.icon_defult_bg).dontAnimate().into(imageView);
            }
        });
        /**
         * 设置轮播图高度
         */
        allHeight2 = Settings.displayWidth / 3;//轮播图高度
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Settings.displayWidth,
                allHeight2);
        layout_banner_carouse2.setLayoutParams(layoutParams);
        /**
         * 轮播图设置
         */
        layout_banner_carouse2.setPageCount(imageList2.size());//轮播图数量

    }

    @Override
    protected void requestData() {

        //        initAdapter();
    }

    private void initHttp() {
        memberHomePst.home(token);
    }

    /**
     * 初始化菜单栏
     */
    private void initBannerMenus() {
        //广告栏下边的菜单
        LinearLayout.LayoutParams layoutParams12 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams
                .MATCH_PARENT, (int) ((float) ScreenUtil.getScreenWidth() / 2.0f));

        //首页菜单分页
        FrameLayout.LayoutParams entrancelayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams
                .MATCH_PARENT, (int) ((float) ScreenUtil.getScreenWidth() / 2.0f + 70));
        ll_view_pager.setLayoutParams(entrancelayoutParams);
        view_pager_fgt_home.setLayoutParams(layoutParams12);
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        //将RecyclerView放至ViewPager中：
        int pageSize = HOME_ENTRANCE_PAGE_SIZE;
        //一共的页数等于 总数/每页数量，并取整。
        int pageCount = (int) Math.ceil(iconList.size() * 1.0 / pageSize);
        List<View> viewList = new ArrayList<View>();
        for (int index = 0; index < pageCount; index++) {
            //每个页面都是inflate出一个新实例
            RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.item_home_entrance_vp,
                    view_pager_fgt_home, false);
            recyclerView.setLayoutParams(layoutParams12);
            recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 5));
            HomeClassifyAdapter entranceAdapter = new HomeClassifyAdapter(getActivity(), iconList, index,
                    HOME_ENTRANCE_PAGE_SIZE);
            recyclerView.setAdapter(entranceAdapter);
            viewList.add(recyclerView);
        }
        HomeViewPagerAdapter adapter = new HomeViewPagerAdapter(viewList);
        view_pager_fgt_home.setAdapter(adapter);
        entrance_indicator_fgt_home.initData(2, 0);
        entrance_indicator_fgt_home.setCurrentPage(0);
        if (iconList.size() > 10) {
            entrance_indicator_fgt_home.setVisibility(View.VISIBLE);
            entrance_indicator_fgt_home.initData(2, 0);
            entrance_indicator_fgt_home.setCurrentPage(0);
        } else {
            entrance_indicator_fgt_home.setVisibility(View.GONE);
        }
        view_pager_fgt_home.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                entrance_indicator_fgt_home.setCurrentPage(position);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            if (requestCode == REQUESTCODE) {
                //                String address_name = data.getStringExtra("address_name");
                //                String address_id = data.getStringExtra("address_id");
                //                tv_home_tittle_city.setText(address_name);
            }
        }
    }

    @Override
    public void onComplete(String requestUrl, String jsonStr) {
        super.onComplete(requestUrl, jsonStr);
        if (requestUrl.contains("home")) {
            //            L.e("=====home=====", jsonStr);
            HomeBean homeBean = GsonUtil.GsonToBean(jsonStr, HomeBean.class);
            if (types == 1) {
                articleList = homeBean.getData().getArticle();
                for (int i = 0; i < articleList.size(); i++) {
                    addList.add(articleList.get(i).getTitle());
                }
                Message message = new Message();
                message.what = 0;
                message.obj = addList;
                handler.sendMessage(message);
                types = 2;
            }
            imageList = homeBean.getData().getHome_pic();
            imageList2 = homeBean.getData().getPic_list();
            iconList = homeBean.getData().getModules();
            recruitList = homeBean.getData().getRecruit();
            initBanner();
            initBanner2();
            initBannerMenus();
            if (recruitList.size() == 0) {
                lv_home.setVisibility(View.GONE);
            } else {
                lv_home.setVisibility(View.VISIBLE);
                initAdapter();
            }
            tv_home_spring_name.setText(homeBean.getData().getHome_recruit().get(0).getTitle());
            tv_home_spring_tittle.setText(homeBean.getData().getHome_recruit().get(0).getTitle_two());
            Glide.with(getActivity()).load(homeBean.getData().getHome_recruit().get(0).getPic()).error(R.mipmap
                    .icon_defult).placeholder(R.mipmap.icon_defult).dontAnimate().into(iv_home_spring);
            tittle_two = homeBean.getData().getHome_recruit().get(1).getTitle();
            tittle_one = homeBean.getData().getHome_recruit().get(0).getTitle();
            tv_home_hot_name.setText(homeBean.getData().getHome_recruit().get(1).getTitle());
            tv_home_hot_tittle.setText(homeBean.getData().getHome_recruit().get(1).getTitle_two());
            Glide.with(getActivity()).load(homeBean.getData().getHome_recruit().get(1).getPic()).error(R.mipmap
                    .icon_defult).placeholder(R.mipmap.icon_defult).dontAnimate().into(iv_home_hot);
            tv_home_tittle_city.setText(homeBean.getData().getCity_name());
            return;
        }
    }

    private void initHeight() {
        view_pager_fgt_home.setFocusable(false);
        view_pager_fgt_home.setClickable(true);
        view_pager_fgt_home.setPressed(false);
        view_pager_fgt_home.setEnabled(true);
        lv_home.setFocusable(false);
        lv_home.setClickable(true);
        lv_home.setPressed(false);
        lv_home.setEnabled(true);

    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        //        L.e("=====y=====", y + "");
        //        L.e("======allHeight=====", allHeight + "");
        if (y <= 0) {
            ll_home_tittle.getBackground().setAlpha(0);
            tv_home_tittle_city.setTextColor(getResources().getColor(R.color.white));
            Drawable nav_up1 = getResources().getDrawable(R.mipmap.icon_location_white);
            nav_up1.setBounds(0, 0, nav_up1.getMinimumWidth(), nav_up1.getMinimumHeight());
            tv_home_tittle_city.setCompoundDrawables(nav_up1, null, null, null);
            ll_home_title_search.setBackgroundResource(R.drawable.shape_home_tittle_bg);
            iv_home_on.setVisibility(View.GONE);
            ll_home_job_setting.setVisibility(View.GONE);
        } else if (y > 0 && y <= 300) {//allHeight
            ll_home_tittle.getBackground().setAlpha(0);
            tv_home_tittle_city.setTextColor(getResources().getColor(R.color.white));
            Drawable nav_up1 = getResources().getDrawable(R.mipmap.icon_location_white);
            nav_up1.setBounds(0, 0, nav_up1.getMinimumWidth(), nav_up1.getMinimumHeight());
            tv_home_tittle_city.setCompoundDrawables(nav_up1, null, null, null);
            ll_home_title_search.setBackgroundResource(R.drawable.shape_home_tittle_bg);
            iv_home_on.setVisibility(View.GONE);
            ll_home_job_setting.setVisibility(View.GONE);
        } else if (y > 300) {
            ll_home_tittle.getBackground().setAlpha(255);
            tv_home_tittle_city.setTextColor(getResources().getColor(R.color.blue));
            Drawable nav_up2 = getResources().getDrawable(R.mipmap.icon_location_blue);
            nav_up2.setBounds(0, 0, nav_up2.getMinimumWidth(), nav_up2.getMinimumHeight());
            tv_home_tittle_city.setCompoundDrawables(nav_up2, null, null, null);
            ll_home_title_search.setBackgroundResource(R.drawable.shape_home_tittle_grey);
            iv_home_on.setVisibility(View.VISIBLE);
            ll_home_job_setting.setVisibility(View.VISIBLE);
        }
        immersionInit();
    }
}
